package com.citicup.backend.webmagic;

import com.citicup.backend.dao.StockDailyMapper;
import com.citicup.backend.entity.StockDaily;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;

import java.text.SimpleDateFormat;

@Component
@Slf4j
public class StockProcessor implements PageProcessor {

    private final Site site = Site.me().setRetryTimes(3).setSleepTime(1000);

    final StockDailyMapper stockDailyMapper;

    @Autowired
    public StockProcessor(StockDailyMapper stockDailyMapper) {
        this.stockDailyMapper = stockDailyMapper;
    }

    @Override
    public void process(Page page) {
        saveStockInfo(page);
    }

    private void saveStockInfo(Page page) {
        Html html = page.getHtml();
        String shangzheng = html.xpath("//*[@class='sixteen wide column']/table/tbody/tr[1]/td[4]/span/text()").toString();
        String shenzheng = html.xpath("//*[@class='sixteen wide column']/table/tbody/tr[2]/td[4]/span/text()").toString();
        String hushen = html.xpath("//*[@class='sixteen wide column']/table/tbody/tr[3]/td[4]/span/text()").toString();
        String zhongxiao = html.xpath("//*[@class='sixteen wide column']/table/tbody/tr[4]/td[4]/span/text()").toString();
        String chuangye = html.xpath("//*[@class='sixteen wide column']/table/tbody/tr[5]/td[4]/span/text()").toString();

        System.err.println("上证指数:" + shangzheng);
        System.err.println("深证成指:" + shenzheng);
        System.err.println("沪深300:" + hushen);
        System.err.println("中小板指:" + zhongxiao);
        System.err.println("创业板指:" + chuangye);

        StockDaily stockDaily = new StockDaily();
        stockDaily.setDate(new SimpleDateFormat("yy-MM-dd").format(System.currentTimeMillis()));
        stockDaily.setCsi300(Double.parseDouble(hushen));
        stockDaily.setGrowthEnterpriseIndex(Double.parseDouble(chuangye));
        stockDaily.setShanghaiCompositeIndex(Double.parseDouble(shangzheng));
        stockDaily.setSmallCupIndex(Double.parseDouble(zhongxiao));
        stockDaily.setShenzhenStockExchangeComponentIndex(Double.parseDouble(shenzheng));

        if (stockDailyMapper.findByDate(stockDaily.getDate()).size() == 0)
            page.putField("StockDaily", stockDaily);

    }

    @Override
    public Site getSite() {
        return site;
    }

}